package test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.widgets.Widgets;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Tcom extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Tcom() {
        super();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("application/text");

		String [] svnLoginInfo = new String[4];
		String [] svnOSprocessInfo = new String[4];	//處理SVN 在OS上用

		int standardCount =0;
		int count =0;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		Session session = null;
		Channel channel = null;
		String sql = ""; 
		String subsysId = "Resource";
		boolean isOL = true;
		try {
			conn = Widgets.getConn();
			
			//取得作用中的次數，並記錄連線資訊
			sql = "SELECT url,id,pwd,path,count,svnExeRepoSN FROM svnExeRepos WHERE subsysId=? AND isOL=? AND isActivated='t'";
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setString(2, isOL?"t":"f");
			rs = ps.executeQuery();
			rs.next();
			for(int i=0;i<4;i++) {
				svnLoginInfo[i] = rs.getString(i+1); 
				System.out.println(svnLoginInfo[i]);
			}
			int oriSvnExeReposSN = rs.getInt("svnExeRepoSN");
			count = rs.getInt("count");
			
			//取得標準次數
			standardCount = Integer.parseInt( Widgets.getSysParameter("svnCount") );
			System.out.println("標準值為："+standardCount);
			System.out.println("目前值為："+count);
			if ( rs!=null ) {rs.close();}
			if ( ps!=null ) {ps.close();}
			
			//若使用次數已大於等於預設的次數，則要更換設定的svn
			if( count >= standardCount ) {
				System.out.println("進入了IF");
				/**
				 * 	取得未作用中，執行時間最舊的SVN，OS連線資訊	
				 * 	將此子系統、isOL下的 SVN 都改為 非作用中
				 *	重建其repo
				 *	將其 執行時間寫入，執行次數歸0，改為作用中
				 **/
				
				//將此SVN 執行時間寫入，執行次數歸0，並改為作用中
				sql = "UPDATE svnExeRepos SET isActivated='f' WHERE svnExeRepoSN=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, oriSvnExeReposSN);
				ps.executeUpdate();
				
				sql = "SELECT url,id,pwd,path,osip,osId,osPwd,repoPath,svnExeRepoSN FROM svnExeRepos WHERE subsysId=? AND isOL=? AND isActivated='f' ORDER BY lastDT ASC,count ASC";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, isOL?"t":"f");
				rs = ps.executeQuery();
				
				if( rs.next() ) {	//因為要取最舊的，故用if就夠了
					for(int i=0;i<4;i++) { svnLoginInfo[i] = rs.getString(i+1); }
					for(int i=0;i<4;i++) { svnOSprocessInfo[i] = rs.getString(i+5); }
				}
				int svnExeRepoSN = rs.getInt("svnExeRepoSN");
				
				if ( ps!=null ) {ps.close();}
				
				//開始重建此Repository
				JSch jsch = new JSch();
				JSch.setConfig("StrictHostKeyChecking", "no");
				System.out.println("要重建repo");
				System.out.println("帳號："+svnOSprocessInfo[1]);
				System.out.println("標的："+svnOSprocessInfo[0]);
				System.out.println("密碼："+svnOSprocessInfo[2]);
				System.out.println("目的："+svnOSprocessInfo[3]);
				session = jsch.getSession(svnOSprocessInfo[1], svnOSprocessInfo[0], 22);
				session.setPassword(svnOSprocessInfo[2]);
				session.connect();
				String command = "rm -rf "+svnOSprocessInfo[3]+";svnadmin create "+svnOSprocessInfo[3]+";chown apache.apache "+svnOSprocessInfo[3]+" -R";
				
				System.out.println("要執行的指令："+command);
				channel = session.openChannel("exec");
				((ChannelExec) channel).setCommand(command);
				channel.connect();
				if ( channel != null ) { if ( channel.isConnected() ) { channel.disconnect(); } }
				if ( session != null ) { if ( session.isConnected() ) { session.disconnect(); } }
			
				
				//將所有的 repo都改為非用中
				sql = "UPDATE svnExeRepos SET isActivated='f' WHERE subsysId=? AND isOL=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, isOL?"t":"f");
				ps.executeUpdate();
				
				
				//將此SVN 執行時間寫入，執行次數歸1，並改為作用中
				sql = "UPDATE svnExeRepos SET isActivated='t',count=1,lastDT=? WHERE svnExeRepoSN=?";
				ps = conn.prepareStatement(sql);
				ps.setTimestamp(1, Widgets.cDT());
				ps.setInt(2, svnExeRepoSN);
				ps.executeUpdate();
			} else {
				//將作用中的SVN 使用次數加一
				sql = "UPDATE svnExeRepos SET count=?,lastDT=? WHERE isActivated='t' AND subsysId=? AND isOL=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, count+1 );
				ps.setTimestamp(2, Widgets.cDT());
				ps.setString(3, subsysId);
				ps.setString(4, isOL?"t":"f");
				ps.executeUpdate();	
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if ( rs!=null ) {rs.close();}
				if ( ps!=null ) {ps.close();}
				if ( conn!=null ) {conn.close();}
				if ( channel != null ) { if ( channel.isConnected() ) { channel.disconnect(); } }
				if ( session != null ) { if ( session.isConnected() ) { session.disconnect(); } }
			} catch(Exception e) {}
		}
		
	
		response.getWriter().write(svnLoginInfo[0]);
	}
}
